package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DishServicelmpl implements DishService {
    @Autowired
    DishMapper dishMapper;
    @Autowired
    DishFlavorMapper dishFlavorMapper;
    @Autowired
    SetmealMapper setmealMapper;
    @Autowired
    SetmealDDMapper setmealDDMapper;

    /**
     * 新增菜品信息
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//事务关联，同时成功同时失败
    public void savedishandflavor(DishDTO dishDTO) {
        log.info("新增菜品信息：{}",dishDTO);
        //创建dish对象，并复制给dishDTO
        Dish dish = Dish.builder().build();
        BeanUtils.copyProperties(dishDTO,dish);
        //新增菜品信息方法
        dishMapper.insertdish(dish);
        //获取菜品id 根据id选择菜品口味
        Long dishid = dish.getId();
        //获取口味集合
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //判断菜品时候含有口味
        if(flavors!=null&&flavors.size()>0){
            //循环遍历口味集合（根据菜品id）
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishid);
            });
            //新增菜品口味方法
            dishFlavorMapper.insertflavor(flavors);
        }


    }

    /**
     * 分页查询菜品
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        log.info("分页查询菜品信息");
        //开启分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        //分页查询的方法
        Page<DishVO> page =dishMapper.findpage(dishPageQueryDTO);
        //页码总记录数
        long total = page.getTotal();
        //当前页数据集合
        List<DishVO> records = page.getResult();

        return new PageResult(total,records);

    }

    /**
     * 起售停售菜品
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletedish(List<Long> ids) {
        //删除菜品信息时要考虑菜品起售状态同时菜品套餐里面还在起售状态下的菜品不能删除
        log.info("批量删除菜品：{}", ids);
        //获取菜品id
        for (Long id : ids) {
            Dish dish = dishMapper.getByids(id);
            //判断当前菜品是否处于起售状态
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //处于起售状态 不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        }
        //判断当前菜品是否能删除，是否关联了
        //获得菜品分类套餐菜品id 定义删除套餐菜品方法
        List<Long> categoryIds = setmealMapper.getsetmealByids(ids);
        if (categoryIds != null && categoryIds.size() > 0) {
            //当前菜品和套餐连接 不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中的数据
        for (Long id : ids) {
            dishMapper.deleteByids(id);
            //根据菜品id删除与被删除菜品有关的口味
            dishFlavorMapper.deleteFlavorByids(id);
        }


    }

    /**
     * 根据菜品id查询菜品口味信息
     * @param id
     * @return
     */
    @Override
    public DishVO getDishByIds(Long id) {
        Dish dish=dishMapper.getByids(id);
        //还需要修改菜品信息时还需要修改口味，因此需要根据id查询该菜品口味
        List<DishFlavor> dishFlavors=dishFlavorMapper.getflavorids(id);
        //将查询到的数据封装在VO
        DishVO dishVO=new DishVO();
        //复制dish的数据给dish
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 修改菜品信息
     * @param dishDTO
     */
    @Override
    public void updateandFlavor(DishDTO dishDTO) {
        //将查询到的数据赋值给dish
        log.info("修改菜品信息:{}",dishDTO);
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改菜品信息
        dishMapper.update(dish);
        //修改菜品时删除其菜品的原有口味数据
        dishFlavorMapper.deleteFlavorByids(dishDTO.getId());
        //重新添加新的口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //判断口味是否为空，遍历口味信息
        if(flavors!=null&&flavors.size()>0){
            flavors.forEach(dishFlavor ->
                    dishFlavor.setDishId(dishDTO.getId()));
        }
        //插入口味信息
        dishFlavorMapper.insertflavor(flavors);

    }
    /**
     * 重新遍历菜品口味信息
     * @param categoryId
     * @param name
     * @return
     */
    @Override
    public List<Dish> list(Integer categoryId, String name) {
        //构建dish对象
        Dish dish = Dish.builder().build();
        //判断分类id是否为空，不为空将分类id给菜品id
        if(categoryId!=null){
            Long categoryId1=(long)categoryId;
            dish.setCategoryId(categoryId1);
        }
        //判断分类name是否为空，不为空将分类name给菜品name，方便在分类表子搜索名字找到菜品
        if(name!=null){
            dish.setName(name);
        }
        //查询时菜品状态只查询菜品正在售的
        dish.setStatus(StatusConstant.ENABLE);
        List<Dish> list = dishMapper.list(dish);
        return list;
    }



    @Override
    public void startstop(Integer status, Long id) {
        //获取dish对象
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.startstop(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getflavorids(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}

